package main

import (
	"bufio"
	"context"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

func main() {
	// 容器 ID 或名称
	containerID := "2ef52f72fd183e059a39ca092b35b478c8ba61c6f9cf92ea8c78f2fe3e4558e9"
	// 日志关键字
	watchword := "账号状态变更为离线"

	// 初始化 Docker 客户端
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		log.Fatalf("Failed to create Docker client: %v", err)
	}

	// 启动日志轮询
	for {
		fmt.Println("Polling logs...")
		err := pollLogs(cli, containerID, watchword)
		if err != nil {
			log.Printf("Error during log polling: %v", err)
		}
		time.Sleep(5 * time.Second) // 每隔 5 秒轮询一次
	}
}

func pollLogs(cli *client.Client, containerID, watchword string) error {
	ctx := context.Background()

	// 获取容器日志
	logs, err := cli.ContainerLogs(ctx, containerID, types.ContainerLogsOptions{
		ShowStdout: true,
		ShowStderr: true,
		Follow:     false,
		Tail:       "20", // 只检查最近 20 行日志
	})
	if err != nil {
		return fmt.Errorf("failed to fetch logs: %v", err)
	}
	defer logs.Close()

	scanner := bufio.NewScanner(logs)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.Contains(line, watchword) {
			fmt.Printf("Detected watchword in logs: %s\n", line)
			// 如果匹配到日志中的关键字，重启容器
			return restartContainer(cli, containerID)
		}
	}

	if err := scanner.Err(); err != nil {
		return fmt.Errorf("error reading logs: %v", err)
	}
	return nil
}

func restartContainer(cli *client.Client, containerID string) error {
	ctx := context.Background()

	fmt.Printf("Restarting container: %s\n", containerID)
	timeout := 10 * time.Second
	if err := cli.ContainerRestart(ctx, containerID, &timeout); err != nil {
		return fmt.Errorf("failed to restart container: %v", err)
	}
	fmt.Printf("Container %s restarted successfully.\n", containerID)
	return nil
}
